# -*- coding: UTF-8 -*-
__license__ = "GPL http://www.gnu.org/licenses/gpl.txt"
__author__="xushengs@gmail.com"
__homepage__ = "http://fdream.net"
__date__ ="2010-2-26 17:39:27"
__version = "0.1"

#from rest import *
import re
from google.appengine.api import urlfetch
from google.appengine.ext import webapp

api_url = 'http://twitter.com'
search_url = 'http://search.twitter.com'

class twitterAPI(webapp.RequestHandler):
    def get(self):
        api(self)
    def post(self):
        api(self)
    def put(self):
        api(self)
    def delete(self):
        api(self)
    def head(self):
        api(self)

def api(handler):
    #return handler.response.out.write('<h1>This is api</h1>')
    req = handler.request
    body = req.body
    path = req.path
    query = req.query_string
    headers = req.headers
    method = req.method

    rc = re.compile('^/search', re.I)
    if rc.search(path):
        url = search_url
    else:
        url = api_url
    rc = re.compile('^/.*?/')
    url = url + rc.sub('/', path)
    
    if query:
        url = url + '?' + query

    if not headers.has_key('Content-Length'):
        #del headers['Content-Length']
        headers['Content-Length'] = len(body)

    try:
        result = urlfetch.fetch(url=url, headers=headers, payload=body, method=method)
        handler.response.headers = result.headers
        return handler.response.out.write(result.content)
    except:
        return handler.response.out.write('{error: "download failed!}')

